// toast
import { isNotEmpty } from './verify'
import { Api_Upload, Token_Key } from '@/config'
import { useUserStore } from '@/store'
import { isCheckTimeout } from '@/util/auth'

export function uploadImage (imageParams = {}) {
  return new Promise(async (resolve, reject) => {
    const userStore = useUserStore()
    if (userStore.token) {
      if (isCheckTimeout()) {
        await showToast({
          title: '登录已超时,请重新进入',
          duration: 2000,
        })
        userStore.logout()
        return
      }
    }
    uni.chooseImage({
      count: 1, // TODO... 暂只支持传一张
      sizeType: imageParams.sizeType || ['compressed'],
      sourceType: imageParams.sourceType || ['camera', 'album'],
      extension: imageParams.extension || null,
      success (uploadRes) {
        const { tempFilePaths } = uploadRes
        uni.uploadFile({
          url: Api_Upload,
          header: {
            [Token_Key]: userStore.token,
          },
          fileType: 'image',
          filePath: tempFilePaths[0],
          success: (uploadFileRes) => {
            console.log(uploadFileRes.data)
            uploadFileRes.data = JSON.parse(uploadFileRes.data)
            if (uploadFileRes.data.succeed) {
              resolve(uploadFileRes.data.data)
            } else {
              showToast({
                title: uploadFileRes.data.msg || '上传失败!',
                duration: 2000,
              })
              reject(uploadFileRes.data)
            }
          },
        })
      },
      fail (e) {
        reject(e)
        console.log(e)
      },
    })
  })
}

export function showLoading({title = '加载中',mask = true}){
  uni.showLoading({
    title: title,
    mask
  })
}
export function hideLoading(){
  uni.hideLoading()
}

export function showToast ({ title, icon, duration }) {
  return new Promise((resolve) => {
    let timer = null
    uni.showToast({
      title: title || '',
      icon: icon || 'none',
      duration: isNotEmpty(duration) ? duration : 1500,
    })
    timer = setTimeout(() => {
      resolve()
      clearTimeout(timer)
    })
  })
}

export function showModal ({ title, content }) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: title || '提示',
      content: content || '',
      success: res => {
        if (res.confirm) {
          resolve()
        } else if (res.cancel) {
          reject()
        }
      },
    })
  })
}

// uni.user
export function uniLogin () {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin', //使用微信登录
      success: loginRes => {
        resolve(loginRes)
      },
      fail: err => {
        reject(err)
      },
    })
  })
}

// uni.getUserInfo
export function uniGetUserInfo () {
  return new Promise((resolve, reject) => {
    uni.getUserInfo({
      provider: 'weixin',
      success: loginRes => {
        resolve(loginRes)
      },
      fail: err => {
        reject(err)
      },
    })
  })
}

//得到元素的size
export function getElSize (id) {
  return new Promise((res, rej) => {
    const query = uni.createSelectorQuery().in(this)
    query.select('#' + id).boundingClientRect(data => {
      console.log(data)
    }).exec()
  })
}

// 网络图片保存相册
export function saveAlbum (url, callback) {
  let result = {}
  uni.downloadFile({
    url: url,
    success: downLoadRes => {
      if (downLoadRes.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: downLoadRes.tempFilePath,
          success: () => {
            result.succeed = true
            uni.showToast({
              icon: 'success',
              title: '保存成功',
            })
            callback && callback(result)
          },
          fail: e => {
            uni.showToast({
              icon: 'success',
              title: '保存失败',
            })
            result.succeed = false
            result.error = e
            console.log(result)
            callback && callback(result)
          },
        })
      } else {
        uni.showToast({
          icon: 'success',
          title: '保存失败',
        })
        result.succeed = false
        result.error = downLoadRes
        console.log(result)
        callback && callback(result)
      }
    },
  })
}

// 相册式预览
export function previewGallery (imgArr, index) {
  let urls = imgArr.map(item => {
    if (item.outAttachmentUrl) {
      return item.outAttachmentUrl
    }
    if (item.outFileUrl) {
      return item.outFileUrl
    }
    if (item.originalUrl) {
      return item.originalUrl
    }

  })
  uni.previewImage({
    urls,
    current: index,
  })
}

// 获取用户位置
export function getUserLocation (params) {
  params = params || {}
  return new Promise((resolve, reject) => {
    uni.authorize({
      //如果没有授权，向用户发起请求
      scope: 'scope.userLocation',
      success: () => {
        uni.getLocation({
          type: params.type || 'gcj02',
          altitude: isNotEmpty(params.altitude) ? params.altitude : false,
          isHighAccuracy: isNotEmpty(params.isHighAccuracy)
            ? params.isHighAccuracy
            : false,
          highAccuracyExpireTime: isNotEmpty(params.highAccuracyExpireTime)
            ? params.highAccuracyExpireTime
            : 3000,
          accuracy: isNotEmpty(params.accuracy) ? params.accuracy : 'high',
          success: res => {
            resolve(res)
          },
          fail: e => {
            reject('e')
          },
        })
      },
      fail: () => {
        reject('获取位置失败')
        uni.showModal({
          title: '提示',
          content: '请打开位置权限',
          success: confirmRes => {
            if (confirmRes.confirm) {
              uni.openSetting({
                //调起客户端小程序设置界面,让用户开启位置
                success: res2 => {
                  uni.navigateBack({
                    delta: 1,
                  })
                  console.log(res2.authSetting)
                },
                fail: e => {
                  console.log(e)
                },
              })
            }
          },
        })
      },
    })
  })
}

// 获取状态栏高度
export function getStatusBarHeight () {
  const phoneInfo = uni.getSystemInfoSync()
  return phoneInfo.statusBarHeight
}

// 获取页面宽度
export function getScreenWidth () {
  const phoneInfo = uni.getSystemInfoSync()
  return phoneInfo.screenWidth
}

// 获取页面高度
export function getScreenHeight () {
  const phoneInfo = uni.getSystemInfoSync()
  return phoneInfo.screenHeight
}

// 获取底部安全距离
export function getSafeArea(direction){

}
